<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\logic;

use app\common\model\EthAccount;
use app\common\model\EthAccountLog;
use app\common\model\OtcCancelLog;
use app\common\model\OtcOrder;
use app\common\model\OtcShop;
use app\common\model\OtcTrading;
use app\common\model\SbNotice;
use app\common\model\ShopAccountLog;
use app\common\model\ShopPoundageLog;
use app\common\model\Transfer;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use app\common\model\UserBadRecord;
use app\common\model\UserBlackRecord;
use app\common\model\UserNotice;
use app\common\model\UserPayType;
use app\common\model\UserRankingData;
use app\common\model\Wallet;
use think\Db;

/**
 * OTC逻辑
 */
class Otc extends AdminBase
{

    /**
     * 获取会员信息
     */
    public function getOtcInfo($where = [], $field = true)
    {

        $info = $this->modelAdvertisers->getInfo($where, $field);

        return $info;
    }



    /**
     * 获取Recharge列表
     */
    public function getTradeList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|s.shop_name'] = $data['search_data'];
        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['type'])) {
            $where['a.type'] = $data['type'];

            if(!empty($data['order'])){
                $where['is_recommend']=1;
            }
        }
        if (  !empty($data['money']) ) {
            $where['a.surplus_total'] = $data['money'];
        }
        if (  !empty($data['state']) ) {
            $where['a.state'] = $data['state'];
        }
        if (  isset($data['state']) && $data['state']=='0' ) {
            $where['a.state'] = $data['state'];
        }
        $where['a.status']=1;
//        dd/**/($where);
        $price=getPrice();
        $eths=[];
        foreach ($price as $k=>$v){
                $arr['name']=$v;
                $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where(['surplus_total'=>$v,'a.status'=>1,'a.state'=>0,'a.wallet_id'=>6,'a.type'=>$data['type']])->count();
                $eths[]=$arr;
        }
        $btcs=[];
        foreach ($price as $k=>$v){
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where(['surplus_total'=>$v,'a.status'=>1,'a.state'=>0,'a.wallet_id'=>7,'a.type'=>$data['type']])->count();
            $btcs[]=$arr;
        }
        $usdts=[];
        foreach ($price as $k=>$v){
            $arr['name']=$v;
            $arr['count']=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where(['surplus_total'=>$v,'a.status'=>1,'a.state'=>0,'a.wallet_id'=>8,'a.type'=>$data['type']])->count();
            $usdts[]=$arr;
        }


        $list =  $this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
        $count=$this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();

        return ['list'=>$list,'count'=>$count,'eths'=>$eths,'btcs'=>$btcs,'usdts'=>$usdts,'price'=>$price];

    }



    /**
     * 导出OTC买卖单列表
     */
    public function exportOtcTradeList($data = [], $field = 'a.*,c.username', $order = 'id asc')
    {

        set_time_limit(0);
        $where = $where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }

        if (!empty($data['search_data'])) {
            $where['a.user_id|c.username|s.shop_name'] = $data['search_data'];
        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['type'])) {
            $where['a.type'] = $data['type'];
        }

        if (  !empty($data['state']) ) {
            $where['a.state'] = $data['state'];
        }


        $list =  $this->modelOtcTrading->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->select();




        foreach ($list as $k => $v) {
			$list[$k]['k'] = $k+1;
            $list[$k]['state_text'] =$v->state_text;
            if($v['state']==1){
                $list[$k]['up_time']='------';
            }else{
                if($v['state']== 3 && !$v['admin_name']){
                    $list[$k]['up_time']='------';
                }else{
                    $list[$k]['up_time']=date('Y-m-d H:i:s',$v->update_time);
                }

            }
        }

//        dd(json_decode(json_encode($list),true));
        $titles = "序号,UID,用户名,交易数量,剩余数量,价格,交易最低金额,交易最高金额,发布时间,状态,审核时间,审核人";
        $keys = "k,id,username,number,surplus_number,price,min_money,max_money,create_time,state_text,up_time,admin_name";
        if($data['type']==1){
            action_log('导出', '导出OTC买单列表');

            export_excel($titles, $keys, $list, 'OTC买单列表');
        }else{
            action_log('导出', '导出OTC卖单列表');

            export_excel($titles, $keys, $list, 'OTC卖单列表');
        }

    }


    /**
     * 买卖单取消
     */
    public function trade_check($data = [])
    {

        Db::startTrans();
        try{
            if(!empty($data['ids'])){
                $result=$this->modelOtcTrading->where(['id'=>['in',$data['ids']]])->update(['is_recommend'=>$data['is_recommend']]);
            }else{
                $info= $this->modelOtcTrading->getInfo(['id'=>$data['id']]);
                if($info['type']==2){
                    if($data['state']==3){
                        //取消订单


                        //退回店铺余额

                        $account=OtcShop::where(['id'=>$info['shop_id']])->lock(true)->find();
                        $account->cancel_number+=$info['surplus_number'];
                        $account->number_lock-=$info['surplus_number'];
                        $account->save();



                    }
                }

                $data['update_time']=time();
                $data['admin_name'] = session('member_info.username');

                $result = $this->modelOtcTrading->setInfo($data);
            }

            Db::commit();
            return $result ? [RESULT_SUCCESS, '操作成功'] : [RESULT_ERROR, '操作失败'];
        }catch (\Exception $e){
            Db::rollback();
            return   [RESULT_ERROR, $e->getMessage()];
        }


    }

    /***
     * 订单详情
     */

    public function trade_detail($data)
    {
        $info = $this->modelOtcTrading->getInfo(['id' => $data['id']]);
        $paylist = [];
        if ($info['is_alipay']) {
            $alipay = $this->modelUserPayType->getInfo(['type' => 1, 'user_id' => $info['user_id'], 'status' => 1]);
            if($alipay){
                $alipay['pay_text'] = '支付宝';
                $alipay['pay_name'] = '支付宝';
                $paylist[]=$alipay;
            }


        }
        if ($info['is_weixin']) {
            $alipay = $this->modelUserPayType->getInfo(['type' => 2, 'user_id' => $info['user_id'], 'status' => 1]);
            if($alipay){
                $alipay['pay_text'] = '微信';
                $alipay['pay_name'] = '微信';
                $paylist[]=$alipay;
            }

        }
        if ($info['is_bank']) {
            $alipay = $this->modelUserPayType->getInfo(['type' => 3, 'user_id' => $info['user_id'], 'status' => 1]);
            if($alipay){
                $alipay['pay_text'] = '银行卡';
                $alipay['pay_name'] =$alipay['opening_bank'];
                $paylist[]=$alipay;
            }

        }
        $info['paylist']=$paylist;
        return $info;
    }



    /**
     * 获取OTC订单列表
     */
    public function getOrderList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where =$where2=$where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =  $data['search_data'];
            $where1['s.shop_name'] =  $data['search_data'];
        }
        if (!empty($data['search_data1'])) {
            $where2['a.uid'] = $data['search_data1'];
            $where2['d.username'] =  $data['search_data1'];
        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['type'])) {
            $where['a.type'] = $data['type'];

        }
        if (!empty($data['pay_type'])) {
            $where['a.pay_type'] = $data['pay_type'];
        }
        if (  !empty($data['state']) ) {
            $where['a.state'] = $data['state'];
        }else{
            $where['a.state'] =['not in',[6,8]];
        }
//        dd($where);
        if (!empty($where1)) {
            if(!empty($where2)){
                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ d' ,'a.uid = d.id')->field($field)->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->order($order)->paginate($paginate, false, ['query' => $data]);
                $count=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ d' ,'a.uid = d.id')->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->count();
            }else{
                $list =  $this->modelOtcOrder->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->order($order)->paginate($paginate, false, ['query' => $data]);
                $count=$this->modelOtcOrder->alias('a')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->count();
            }

        } else {

            if(!empty($where2)){

                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ d' ,'a.uid = d.id')->field($field)->where($where)->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->order($order)->paginate($paginate, false, ['query' => $data]);

                $count=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->join('__MEMBER__ d' ,'a.uid = d.id')->where($where)->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->count();
            }else{
                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
                $count=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->count();
            }

        }


        $where['a.wallet_id']=1;
        $esp=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');
        $where['a.wallet_id']=6;
        $eth=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');
        $where['a.wallet_id']=7;
        $btc=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');
        $where['a.wallet_id']=8;
        $usdt=$this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->sum('number');
        return ['list'=>$list,'count'=>$count,'ect'=>$eth+0,'btc'=>$btc+0,'usdt'=>$usdt+0,'esp'=>$esp+0];

    }


    /**
     * 导出OTC订单列表
     */
    public function exportOtcOrderList($data = [], $field = 'a.*,c.username', $order = 'id asc')
    {

        set_time_limit(0);
        $where =$where2=$where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =  $data['search_data'];
        }
        if (!empty($data['search_data1'])) {
            $where2['a.uid'] = $data['search_data1'];
            $where2['d.username'] =  $data['search_data1'];
        }
        if (!empty($data['wallet_id'])) {
            $where['a.wallet_id'] = $data['wallet_id'];
        }
        if (!empty($data['type'])) {
            $where['a.type'] = $data['type'];
        }
        if (!empty($data['pay_type'])) {
            $where['a.pay_type'] = $data['pay_type'];
        }
        if (  !empty($data['state']) ) {
            $where['a.state'] = $data['state'];
        }else{
            $where['a.state'] = ['not in',[6,8]];
        }
        if (!empty($where1)) {
            if(!empty($where2)){
                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__MEMBER__ d' ,'a.uid = d.id')->field($field)->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->order($order)->select();
            }else{
                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                    $q->whereOr($where1);
                })->order($order)->select();
            }

        } else {

            if(!empty($where2)){

                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__MEMBER__ d' ,'a.uid = d.id')->field($field)->where($where)->where(function ($q)use($where2){
                    $q->whereOr($where2);
                })->order($order)->select();


            }else{
                $list =  $this->modelOtcOrder->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->select();
            }

        }


        foreach ($list as $k => $v) {
            $list[$k]['k'] = $k+1;
            $list[$k]['state_text'] =$v->state_text;
            $list[$k]['usernickname'] =$v->user->username;
        }

//        dd(json_decode(json_encode($list),true));
        $titles = "序号,买家用户名,交易数量,价格,交易时间,状态,卖家用户名";
        $keys = "k,username,number,price,create_time,state_text,usernickname";

        action_log('导出', '导出OTC订单列表');

        export_excel($titles, $keys, $list, 'OTC订单列表');


    }


    /**
     * 获取OTC订单列表
     */
    public function getOrderFeedBackList($data = [], $field = 'a.*,c.username ', $order = '', $paginate = DB_LIST_ROWS)
    {



        $where =$where2=$where1 = [];
        if (!empty($data['date1']) && !empty($data['date2']) ) {
            $where['a.create_time'] = ['between', [strtotime($data['date1'] . ' 00:00:00'), strtotime($data['date2'] . ' 23:59:59')]];
        }
        if (!empty($data['search_data'])) {
            $where1['a.user_id'] = $data['search_data'];
            $where1['c.username'] =  $data['search_data'];
        }

        if (  !empty($data['state']) ) {
            $where['a.state'] = $data['state'];
        }
        if (!empty($where1)) {

            $list =  $this->modelOtcFeedback->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->order($order)->paginate($paginate, false, ['query' => $data]);
            $count=$this->modelOtcFeedback->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->where(function ($q)use($where1){
                $q->whereOr($where1);
            })->count();


        } else {


            $list =  $this->modelOtcFeedback->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->field($field)->where($where)->order($order)->paginate($paginate, false, ['query' => $data]);
            $count=$this->modelOtcFeedback->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->where($where)->count();


        }

        return ['list'=>$list,'count'=>$count];

    }


    /**
     * 申诉订单处理
     */
    public function order_check($data = [])
    {
        $url=url('trade_order_appeal_list');
        Db::startTrans();
        try{
            $info= $this->modelOtcFeedback->getInfo(['id'=>$data['id']]);
            $order=$info->otcorder;
            //修改申诉状态

            switch ($data['real']){
                case '0':
                    $feedback_type='买家已打款';
                    $state1=2;
                    $state=9;
                    break;
                case '1':
                    $state1=2;
                    $feedback_type='店铺已放行';
                    $state=10;
                    break;
                case '2':
                    $state1=5;
                    $state=11;
                    $feedback_type='买家未打款';
                    break;
                case '3':
                    $state1=1;
                    $feedback_type='买家二次打款';
                    $state=12;
                    break;
                case '4':
                    $state1=13;
                    $state=13;
                    $feedback_type='店铺打款超时，转移重新匹配订单';
                    break;
                case '5':
                    $state1=2;
                    $state=14;
                    $feedback_type='结束订单(完成)';
                    break;
            }
            $sell_userid=$order['uid'];
            $buy_userid=$order['user_id'];
            $time=time();
            $arr=[
                'update_time'=>$time ,
                'state'=>$state,
                'feedback_type'=>$feedback_type,
                'feedback_content'=>$data['feedback_content']
            ];
            if($state1==5  ){

                //取消退回
                if($order['otc_type']==1){
                    //退币
                    Db::name('transfer')->where(['id'=>$order['withdrwal_id']])->setInc('money',$order['total']);
                    //待匹配
                    Db::name('transfer')->where(['id'=>$order['withdrwal_id']])->update(['state'=>4]);
                }
                Db::name('otc_trading')->where(['id'=>$order['otc_id']])->setInc('feed_count',1);
                Db::name('otc_trading')->where(['id'=>$order['otc_id']])->update(['state'=>0]);
                Db::name('otc_trading')->where(['id'=>$order['otc_id']])->setInc('surplus_number',$order['number']);
                Db::name('otc_trading')->where(['id'=>$order['otc_id']])->setInc('surplus_total',$order['total']);


            }elseif($state1==2  ){


                //发币
                //扣除卖家冻结余额
                $do=$order->wallet['symbol'].'_do';


                //写入流水


                //买家余额增加

                $arr['receive_time']=$time;

                if($order['otc_type']==1){
                    $log['remark']='店铺代发买入';
                    $order->shop->number_do+=$order['number'];
                    ShopAccountLog::create([
                        'user_id'=>$order->shop['user_id'],
                        'number'=>$order['number'],
                        'shop_id'=>$order['shop_id'],
                        'remark'=> '购买代发金额',
                        'is_add'=>1,
                        'type'=>4
                    ]);

                }else{

                    $user_account=UserAccount::where(['user_id'=>$order['user_id'],'wallet_id'=>1])->lock(true)->find();
                    $money=$order['total'];
                    $user_account->balance+=$money;
                    $user_account->save();

                    //写入流水
                    UserAccountLog::create([
                        'user_id' => $info->user_id,
                        'number' => $money,
                        'wallet_id' =>1,
                        'before_blance' => $user_account->balance -$money,
                        'after_blance' => $user_account->balance,
                        'is_add' => 1,
                        'type' => 24,
                        'remark' =>'OTC买入',

                    ]);
                    //冻结余额减少
                    $order->shop->number_lock-=$order['number'];

                }
                $receive_minute=ceil(($time-$order->getData('pay_time'))/60);
                SbNotice::create([
                    'type'=>2,
                    'shop_name'=>$order->shop->shop_name,
                    'number'=>$order['number'],
                    'receive_minute'=>$receive_minute,
                    'order_id'=>$order['id'],
                    'user_id'=>$order['user_id'],
                    'wallet_id'=>$order['wallet_id'],

                ]);


                $arr['receive_minute']=$receive_minute;
                //更新卖家成交量，发放手续费
                $order->shop->success_count+=1;
                if($order['poundage_number']){
                    $order->shop->poundage_number+=$order['poundage_number'];
                    ShopPoundageLog::create([
                        'user_id'=>$order->shop['user_id'],
                        'shop_id'=>$order['shop_id'],
                        'order_id'=>$order['id'],
                        'otc_id'=>$order['otc_id'],
                        'type'=>$order['withdrwal_id']>0?2:1,
                        'number'=>$order['poundage_number'],
                        'total'=>$order['poundage_number']*$order['price'],
                    ]);


                }
                if($order->trade->feed_count>0){
                    $order->trade->feed_count=0;
                    $order->trade->save();
                }
                if($order->trade->surplus_number==0){
                    $trade_count= Db::name('otc_order')->where(['otc_id'=>$order['otc_id'],'state'=>['in',[1,3,6,7,8]]])->count();
                    if($trade_count>=1){
                        //改变买卖单状态 已完成
                        $order->trade->state=2;
                        $order->trade->save();
                    }
                }

                $order->shop->number_do+=$order['poundage_number'];
                $msg= $order->otc_type==1?'代发':'代收';
                ShopAccountLog::create([
                    'user_id'=>$order->shop['user_id'],
                    'number'=>$order['poundage_number'],
                    'shop_id'=>$order['shop_id'],
                    'remark'=> $msg.'手续费: 0.2%',
                    'is_add'=>1,
                    'type'=>3
                ]);
                $order->shop->turnover+=$order['total'];
                $order->shop->save();

            }elseif($state1==1){
                //买家二次付款
                $arr['state']=1;
                $time=time()+getConfig('otc_last_time')*60;
                $arr['pay_expire_time']=$time;
                $arr['is_second']=1;
                if($order['withdrwal_id']>0){
                    //待付款
                    Db::name('transfer')->where(['id'=>$order['withdrwal_id']])->update(['state'=>5]);

                }

            }elseif ($state1==13){
                $arr['state']=13;
                //转移订单

                $where=['c.is_black'=>0,'a.type'=>$order['otc_type']];
                if($order['otc_type']==1){
                    $ids1=Member::where(['path'=>['like',','.$order['uid'].',']])->column('id');
                    $ids2=explode(',',rtrim($order->member['path'], ","));
                }else{
                    $ids1=Member::where(['path'=>['like',','.$order['user_id'].',']])->column('id');
                    $ids2=explode(',',rtrim($order->user['path'], ","));
                }

                $ids=array_merge($ids1,$ids2);
                $where['a.user_id']=['not in',$ids];
                $where['s.is_match']=1;
                $where['a.state']=0;
                $where['a.surplus_total']=$order['total'];
                $where['s.shop_switch']=1;
                $where['a.status']=1;
                $where['c.start_time_int']=['neq',0];
                $where['c.start_time_int']=['lt',TIME_NOW];
                $where['c.end_time_int']=['neq',0];
                $where['c.end_time_int']=['gt',TIME_NOW];
                $trade=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,match_count,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->lock(true)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();
                if(!$trade){
                    unset( $where['a.user_id']);
                    $where['c.is_company']=1;
                    if($order['otc_type']==1){
                        $where['a.user_id']=['neq',$order['user_id']];
                    }else{
                        $where['a.user_id']=['neq',$order['uid']];
                    }

                    $trade=OtcTrading::alias('a')->field("a.*,surplus_total AS new_price,match_count,a.surplus_number , a.price as all_price")->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->order("feed_count desc ,match_count asc ,price asc ,id asc")->find();

                }

                if(!$trade && $order['otc_type']==2){

                    $number=$order['number'];
                    $where1['a.wallet_id']=$order['wallet_id'];
                    $where1['a.user_id']=['not in',$ids];
                    $where1['c.is_black']=0;
                    $where1['a.is_match']=1;
                    $where1['a.is_release']=1;
                    $where1['a.state']=2;
                    $where1['a.number_total']=['>=',$number];
                    $where1['a.shop_switch']=1;
                    $where1['c.single_amount']=$order['total'];
                    $where1['c.start_time_int']=['neq',0];
                    $where1['c.start_time_int']=['lt',TIME_NOW];
                    $where1['c.end_time_int']=['neq',0];
                    $where1['c.end_time_int']=['gt',TIME_NOW];
                    $shop_info=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->order('c.atuo_count asc,a.id desc')->find();
                    if(!$shop_info){
                        unset( $where1['a.user_id']);
                        $where1['c.is_company']=1;
                        $where1['a.user_id']=['neq',$order['user_id']];


                        $shop_info=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->order('c.atuo_count asc,a.id desc')->find();
                        if(!$shop_info){
                            unset( $where1['c.single_amount']);
                            //智能化
                            $where1['c.is_intellect']=1;
                            $shop_info=$this->modelOtcShop->alias('a')->join('__MEMBER__ c' ,'a.user_id = c.id')->order('c.atuo_count asc,a.id desc')->find();
                        }
                    }

                    if($shop_info){
                        //创建出售订单
                        $ali_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>1,'status'=>1,'is_use'=>1])->count();
                        $weichat_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>2,'status'=>1,'is_use'=>1])->count();
                        $bank_pay=UserPayType::where(['user_id'=>$shop_info['user_id'],'type'=>3,'status'=>1,'is_use'=>1])->count();


                        //生成订单
                        $res=$this->modelOtcTrading->setInfo([
                            'type'=>2,
                            'shop_id'=>$shop_info['id'],
                            'number'=>$number,
                            'wallet_id'=>$shop_info['wallet_id'],
                            'price'=>$order->wallet['parities'],
                            'surplus_number'=>$number,
                            'total'=>$order['total'],
                            'surplus_total'=>$order['total'],
                            'remark'=>'店铺自动化生成',
                            'user_id'=>$shop_info['user_id'],
                            'is_alipay'=>$ali_pay>0?1:0,
                            'is_weixin'=>$weichat_pay>0?1:0,
                            'is_bank'=>$bank_pay>0?1:0,
                            'is_auto'=>1

                        ]);
                        if($number>$shop_info->cancel_number){
                            $second_number=$number-$shop_info->cancel_number;
                            $shop_info->cancel_number=0;
                            $shop_info->number_do-=$second_number;
                        }else{
                            $shop_info->cancel_number-=$number;
                        }

                        $shop_info->number_lock+=$number;
                        $shop_info->member->atuo_count+=1;
                        $shop_info->member->save();
                        $shop_info->save();
                        $trade=$this->modelOtcTrading->alias('a')->field("a.*,surplus_total AS new_price,match_count,a.surplus_number , a.price as all_price")->where(['id'=>$res])->find();


                    }
                }
                if(!$trade){
                    Db::rollback();
                    return   [RESULT_ERROR, '暂无订单适合转移'];
                }
                $pays=$payids=[];
                $ali_pay=UserPayType::where(['user_id'=>$order['uid'],'type'=>1,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                $count=0;
                if($ali_pay){
                    if(count($ali_pay)>1){
                        foreach ($ali_pay as $k=>$v){
                            $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>1,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$v['id'].',%']])->sum('total')+0;
                            if($money>$v['max_money']){
                                continue;
                            }else{
                                $payids[]=$v['id'];
                                $v['image']=$v->image;
                                $pays[]=$v;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>1,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$ali_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$ali_pay[0]['max_money']){

                            $payids[]=$ali_pay[0]['id'];
                            $ali_pay[0]['image']=$ali_pay[0]->image;
                            $pays[]=$ali_pay[0];
                            $count++;
                        }

                    }



                }
                $wechat_pay=UserPayType::where(['user_id'=>$order['uid'],'type'=>2,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                if($wechat_pay){
                    if(count($wechat_pay)>1){
                        foreach ($wechat_pay as $k=>$v){
                            $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$v['id'].',%']])->sum('total')+0;
                            if($money>$v['max_money']){
                                continue;
                            }else{
                                $payids[]=$v['id'];
                                $v['image']=$v->image;
                                $pays[]=$v;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$wechat_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$wechat_pay[0]['max_money']){

                            $payids[]=$wechat_pay[0]['id'];
                            $wechat_pay[0]['image']=$wechat_pay[0]->image;
                            $pays[]=$wechat_pay[0];
                            $count++;
                        }

                    }

                }

                $bank_pay=UserPayType::where(['user_id'=>$order['uid'],'type'=>3,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
                if($bank_pay){

                    if(count($bank_pay)>1){
                        foreach ($bank_pay as $k=>$v){
                            $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>3,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$v['id'].',%']])->sum('total')+0;
                            if($money>$v['max_money']){
                                continue;
                            }else{
                                $payids[]=$v['id'];
                                $pays[]=$v;
                                $count++;
                                break;

                            }
                        }
                    }else{
                        $money=OtcOrder::where(['uid'=>$order['uid'],'state'=>['not in',[4,5,13]],'pay_type'=>3,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$bank_pay[0]['id'].',%']])->sum('total')+0;
                        if($money<$wechat_pay[0]['max_money']){

                            $payids[]=$bank_pay[0]['id'];
                            $pays[]=$bank_pay[0];
                            $count++;
                        }

                    }
                }
                if($count==0){
                    //禁止匹配
                    $shop=OtcShop::get(['id'=>$info['shop_id']]);
                    if($shop['no_match_time']>time()){
                        $shop['no_match_time']+=86400;
                    }else{
                        $shop['no_match_time']=86400;
                    }
                    $shop->is_match=0;
                    $shop->save();
                    OtcCancelLog::create([
                        'username'=>$order->member['username'],
                        'mobile'=>$order->member['mobile'],
                        'area'=>$order->member['area'],
                        'number'=>1,
                        'type'=>3,
                        'shop_id'=>$shop['id'],
                        'remark'=>'OTC限制店铺匹配(收款金额超过每日限制)',
                        'user_id'=>$order->member['id']
                    ]);
                    Db::commit();
                    return   [RESULT_ERROR, '转移订单超过每日收款限额,请重新转移'];
                }
                if($payids){
                    UserPayType::where(['id'=>['in',$payids]])->setInc('use_count',1);
                }
                $arrs=[
                    'price'=>$order['price'],
                    'wallet_id'=>$trade['wallet_id'],
                    'pay_expire_time'=>$time+getConfig('otc_last_time')*60,
                    'otc_type'=>$order['otc_type'],
                    'shop_id'=>$trade['shop_id'],
                    'otc_id'=>$trade['id'],
                    'user_id'=>$trade['user_id'],
                    'uid'=>$order['uid'],
                    'total'=>$order['total'],
                    'number'=>$order['number'],
                    'order_id'=>$order['id'],
                    'withdrwal_id'=>$order['withdrwal_id'],
                    'state'=>1,
                    'pay_json'=>json_encode($pays),
                    'channel'=>'CCIE'

                ];

                OtcOrder::create($arrs);
                $trade->state=1;
                $trade->match_count+=1;
                $trade->save();
                if($order['withdrwal_id']>0){
                    //待付款
                    Db::name('transfer')->where(['id'=>$order['withdrwal_id']])->update(['state'=>5]);

                }

            }


            //            //冻结机制
            if(!empty($data['freeze'])){
                if($data['freeze'] == 2){
                    //冻结卖家账号
                    $this->modelMember->where(["id"=>$sell_userid])->update(["is_black"=>1]);
                    //插入冻结记录
                    $data1 = array(
                        'user_id'=>$sell_userid,
                        'admin_name'=>session('member_info.username'),
                        'remark'=>'因OTC交易违反规则，被买家投诉，被客服处理封号，如有问题，请联系客服处理'
                    );
                    UserBlackRecord::create($data1);
                }elseif($data['freeze'] == '1'){
                    //冻结买家账号
                    $this->modelMember->where(["id"=>$buy_userid])->update(["is_black"=>1]);
                    //插入冻结记录
                    $data1 = array(
                        'user_id'=>$buy_userid,
                        'admin_name'=>session('member_info.username'),
                        'remark'=>'因OTC交易违反规则，被买家投诉，被客服处理封号，如有问题，请联系客服处理',
                    );
                    UserBlackRecord::create($data1);
                }
            }

            if(!empty($data['punish'])) {
                //惩罚机制
                if ($data['punish'] == 2) {
                    //扣除卖家惩罚金

                    $punish = (int)getConfig('otc_sell_penalty');
                    if ($punish) {
                        $user_account = UserAccount::check(['wallet_id' => 1, 'user_id' => $sell_userid]);
                        if ($punish > $user_account['balance']) {
                            UserAccountLog::create([
                                'user_id' => $sell_userid,
                                'number' => $user_account->balance,
                                'remark' => '扣除家惩罚金',
                                'wallet_id' => 1,
                                'before_blance' => $user_account->balance,
                                'after_blance' => 0,
                                'is_add' => 2,
                                'type' => 28
                            ]);

                            //冻结卖家账号
                            $this->modelMember->where(["id" => $sell_userid])->update(["is_black" => 1]);
                            //插入冻结记录
                            $data1 = array(
                                'user_id' => $sell_userid,
                                'admin_name' => session('member_info.username'),
                                'remark' => '因OTC交易违反规则，被买家投诉，惩罚金不足,被客服处理封号，如有问题，请联系客服处理'
                            );
                            UserBlackRecord::create($data1);
                            $user_account->balance = 0;
                            $user_account->save();
                        } else {
                            $user_account->balance -= $punish;
                            $user_account->save();
                            UserAccountLog::create([
                                'user_id' => $sell_userid,
                                'number' => $punish,
                                'remark' => '因OTC交易违反规则，被买家投诉，惩罚金不足,被客服处理封号，如有问题，请联系客服处理',
                                'wallet_id' => 1,
                                'before_blance' => $user_account->balance + $punish,
                                'after_blance' => $user_account->balance,
                                'is_add' => 2,
                                'type' => 28
                            ]);
                        }
                    }

                } elseif ($data['punish'] == 1) {
                    //扣除买家惩罚金
                    $punish = (int)getConfig('otc_sell_penalty');
                    if ($punish) {
                        $user_account = UserAccount::check(['wallet_id' => 1, 'user_id' => $buy_userid]);
                        if ($punish > $user_account['balance']) {
                            UserAccountLog::create([
                                'user_id' => $buy_userid,
                                'number' => $user_account->balance,
                                'remark' => '扣除买家惩罚金',
                                'wallet_id' => 1,
                                'before_blance' => $user_account->balance,
                                'after_blance' => 0,
                                'is_add' => 2,
                                'type' => 28
                            ]);

                            //冻结卖家账号
                            $this->modelMember->where(["id" => $buy_userid])->update(["is_black" => 1]);
                            //插入冻结记录
                            $data1 = array(
                                'user_id' => $buy_userid,
                                'admin_name' => session('member_info.username'),
                                'remark' => '惩罚金不足,封买家号'
                            );
                            UserBlackRecord::create($data1);
                            $user_account->balance = 0;
                            $user_account->save();
                        } else {
                            $user_account->balance -= $punish;
                            $user_account->save();
                            UserAccountLog::create([
                                'user_id' => $buy_userid,
                                'number' => $punish,
                                'remark' => '扣除买家惩罚金',
                                'wallet_id' => 1,
                                'before_blance' => $user_account->balance + $punish,
                                'after_blance' => $user_account->balance,
                                'is_add' => 2,
                                'type' => 28
                            ]);
                        }
                    }
                }
            }

            if(!empty($data['buy_days'])){
                //限制买家otc交易天数
                if($data['buy_days']>0){
                    $member=\app\common\model\Member::get(['id'=>$buy_userid]);
                    $member['is_otc']=0;
                    if($member['penalty_time']>time()){

                        $member['penalty_time']+=$data['buy_days']*86400;
                    }else{
                        $member['penalty_time']=time()+$data['buy_days']*86400;
                    }
                    $member->save();
                    OtcCancelLog::create([
                        'username'=>$member['username'],
                        'mobile'=>$member['mobile'],
                        'area'=>$member['area'],
                        'number'=>$data['buy_days'],
                        'type'=>1,
                        'remark'=>'OTC限制购买(违反规则)',
                        'user_id'=>$member['id']
                    ]);
                }
            }

            if(!empty($data['credit'])){
               //店铺信用分
            }
            if(!empty($data['shop_days'])){
                $member=\app\common\model\Member::get(['id'=>$sell_userid]);
                //限制店铺发布订单天数
                if($data['shop_days']>0){
                    $shop=OtcShop::get(['id'=>$order['shop_id']]);
                    if($shop['penalty_time']>time()){
                        $shop['penalty_time']+=$data['shop_days']*86400;
                    }else{
                        $shop['penalty_time']=time()+$data['shop_days']*86400;
                    }
                    $shop->is_release=0;
                    $shop->save();
                    OtcCancelLog::create([
                        'username'=>$member['username'],
                        'mobile'=>$member['mobile'],
                        'area'=>$member['area'],
                        'number'=>$data['shop_days'],
                        'type'=>2,
                        'shop_id'=>$shop['id'],
                        'remark'=>'OTC限制店铺发布(违反OTC规则)',
                        'user_id'=>$member['id']
                    ]);
                }
            }
            if(!empty($data['no_match_days'])){
                $member=\app\common\model\Member::get(['id'=>$sell_userid]);
                //限制店铺匹配天数
                if($data['no_match_days']>0){
                    $shop=OtcShop::get(['id'=>$order['shop_id']]);
                    if($shop['no_match_time']>time()){
                        $shop['no_match_time']+=$data['no_match_days']*86400;
                    }else{
                        $shop['no_match_time']=time()+$data['no_match_days']*86400;
                    }
                    $shop->is_match=0;
                    $shop->save();
                    OtcCancelLog::create([
                        'username'=>$member['username'],
                        'mobile'=>$member['mobile'],
                        'area'=>$member['area'],
                        'number'=>$data['no_match_days'],
                        'type'=>3,
                        'shop_id'=>$shop['id'],
                        'remark'=>'OTC限制店铺匹配(违反规则)',
                        'user_id'=>$member['id']
                    ]);
                }
            }
            $data['state']=2;
            $data['update_time']=time();
            $result = $this->modelOtcFeedback->setInfo($data);
            if($order['otc_type']==1){
                user_notice($order['user_id'],'您的代发申诉订单已处理完毕');
                user_notice($order['uid'],'您的提现申诉订单已处理完毕');
            }else{
                user_notice($order['user_id'],'您在'.$order['create_time'].'时间有一笔法币交易订单，被商家'.$order->shop['shop_name'].'投诉，投诉原因:'.$info['content'].'，均由客服处理的结果是（'.$feedback_type.'），请知悉。');
                user_notice($order['uid'],'您的店铺申诉订单已处理完毕');
            }
            //修改订单状态
            Db::name('otc_order')->where(['id'=>$info['order_id']])->update($arr);
            Db::commit();
            return $result ? [RESULT_SUCCESS, '操作成功',$url] : [RESULT_ERROR, '操作失败'];
        }catch (\Exception $e){
            Db::rollback();
            return   [RESULT_ERROR, $e->getMessage()];
            return   [RESULT_ERROR, '服务器繁忙'];
        }


    }
    public function trade_add($data)
    {
        $user_name_list = explode("\r\n", $data['username']);
        $money_list = explode("\r\n", $data['money']);
        if (empty($user_name_list)) {
            return [RESULT_ERROR, '会员账号不能为空，请重新输入'];

        }
        if (empty($money_list)) {
            return [RESULT_ERROR, '金额不能为空，请重新输入'];
        }
        if (count($user_name_list) != count($money_list)) {
            return [RESULT_ERROR, '会员账号和金额数量行数不相等'];
        }

        if ($data['price']<=0) {
            return [RESULT_ERROR, '价格不能为0，请重新输入'];
        }
        $wallet_id=explode('-',$data['wallet_id'])[0];
        $min_money=getConfig('otc_min_money');
        $max_money=getConfig('otc_max_money');
        $otc_price=getPrice();
        Db::startTrans();
        try {
            //生成订单


            foreach ($user_name_list as $k => $v) {
                if( !in_array($money_list[$k],$otc_price )){
                    Db::rollback();
                    return [RESULT_ERROR, $money_list[$k].'金额不符合'];
                }
                if($money_list[$k]<$min_money ){
                    Db::rollback();
                    return [RESULT_ERROR, '金额必须大于等于'.$min_money];
                }
                if($money_list[$k]>$max_money ){
                    Db::rollback();
                    return [RESULT_ERROR, '金额必须小于等于'.$max_money];
                }
                $member = $this->modelMember->getInfo(['username|mobile' => $v]);
                if (!$member) {
                    Db::rollback();
                    return [RESULT_ERROR, '会员账号不存在，请重新输入'];
                }
                if ($member['is_company'] != 1) {
                    Db::rollback();
                    return [RESULT_ERROR, $v . '不是公司账号'];
                }

                $shop=OtcShop::get(['state'=>2,'user_id'=>$member['id'],'wallet_id'=>$wallet_id]);
                if(!$shop){
                    Db::rollback();
                    return [RESULT_ERROR, $v . '没有商铺'];
                }
                $is_alipay=$is_weixn=$is_bank=0;
                foreach ($data['pay'] as $ke => $va) {
                    switch ($ke){
                        case 1:
                            if ($va = 'on') {
                                $is_alipay=1;
                            }

                            break;
                        case 2:
                            if ($va = 'on') {
                                $is_weixn=1;
                            }
                            break;
                        case 3:
                            if ($va = 'on') {
                                $is_bank=1;
                            }
                            break;
                    }



                }

                //生成订单
                $new_arr=[
                    'type'=>$data['type'],
                    'user_id'=>$member['id'],
                    'shop_id'=>$shop['id'],
                    'price'=>$data['price'],
                    'number'=>$money_list[$k]/$data['price'],
                    'surplus_number'=>$money_list[$k]/$data['price'],
                    'surplus_total'=>$money_list[$k],
                    'total'=>$money_list[$k],
                    'wallet_id'=>$shop['wallet_id'],
                    'remark'=>'后台生成',
                    'is_alipay'=>$is_alipay,
                    'is_weixin'=>$is_weixn,
                    'is_bank'=>$is_bank
                ];
                if(isset($data['is_recommend'])){
                    $new_arr['is_recommend']=$data['is_recommend'];
                }
                if($data['type']==2){
                    $shop->number_lock+=$money_list[$k]/$data['price'];
                    $shop->save();
                }
                OtcTrading::create($new_arr);

            }

            if($data['type']==1){
                $url =url('otc/trade_list');
            }else{
                $url =url('otc/trade_sell_list');
            }
            Db::commit();
            return [RESULT_SUCCESS, '提交成功,等待审核', $url];
        } catch (\Exception $e) {
            Db::rollback();
            return [RESULT_ERROR, $e->getMessage()];
        }
    }



    /***
     * OTC交易订单生成
     */
    public  function  otc_order_edit($data){

        $user_name_list = explode("\r\n",$data['username']);
        $money_list = explode("\r\n",  $data['money']);
        $channel=explode(',',$data['channel']);
        if (empty($user_name_list)) {
            return  [RESULT_ERROR, '会员账号不能为空，请重新输入'];

        }
        if (empty($money_list)) {
            return  [RESULT_ERROR, '金额不能为空，请重新输入'];
        }
        if (count($user_name_list) != count($money_list)) {
            return  [RESULT_ERROR, '会员账号和金额数量行数不相等'];
        }
        $otc_price=getPrice();
        Db::startTrans();
       foreach ($user_name_list as $k=>$v) {
           $member = $this->modelMember->getInfo(['username|mobile' => $v]);
           if (!$member) {
               Db::rollback();
               return [RESULT_ERROR, '会员账号不存在，请重新输入'];
           }

           if( !in_array($money_list[$k],$otc_price )){
               Db::rollback();
               return [RESULT_ERROR, $money_list[$k].'金额不符合'];
           }
           if ($member['is_company'] != 1) {
               Db::rollback();
               return [RESULT_ERROR, $v . '不是公司账号'];
           }
           $pay_list = $this->modelUserPayType->where(['user_id' => $member['id'], 'status' => 1, 'type' => ['lt', 4]])->select();
           if (empty($pay_list)) {
               Db::rollback();
               return [RESULT_ERROR, '请先添加支付方式'];
           }
           try {
               //生成订单
                $money=$money_list[$k];
               $ids1=Member::where(['path'=>['like','%,'.$member['id'].',%']])->column('id');
               $ids2=explode(',',rtrim($member['path'], ","));
               $ids=array_merge($ids1,$ids2);
               $where['a.type']=2;
               $where['a.user_id']=['not in',$ids];
               $where['a.state']=0;
               $where['a.surplus_total']=$money;
               $where['c.is_black']=0;
               $where['s.is_match']=1;
               $where['a.status']=1;
               $where['s.shop_switch']=1;
               $where['c.start_time_int']=['neq',0];
               $where['c.start_time_int']=['lt',TIME_NOW];
               $where['c.end_time_int']=['neq',0];
               $where['c.end_time_int']=['gt',TIME_NOW];
               $order=$this->modelOtcTrading->alias('a')->field('a.*')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->lock(true)->order('feed_count desc ,match_count asc ,price asc ,a.id asc')->find();
               if(!$order){
                   unset( $where['a.user_id']);
                   $where['c.is_company']=1;
                   $where['a.user_id']=['neq',$member['id']];
                   $order=$this->modelOtcTrading->alias('a')->field('a.*')->join('__MEMBER__ c' ,'a.user_id = c.id')->join('__OTC_SHOP__ s' ,'a.shop_id = s.id')->where($where)->lock(true)->order('feed_count desc ,match_count asc ,price asc ,a.id asc')->find();
               }

               if(!$order){
                   Db::rollback();
                   return [RESULT_ERROR, $v . '暂无订单匹配'];
                   break;
               }
               $time=time()+getConfig('otc_last_time')*60;

               //买单总价等于提现金额
               $number= $order->surplus_number;
               $pays=$payids=[];
               $ali_pay=UserPayType::where(['user_id'=>$order['user_id'],'type'=>1,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
               $count=0;
               if($ali_pay){
                   if(count($ali_pay)>1){
                       foreach ($ali_pay as $ke=>$va){
                           $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>1,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                           if($money>$va['max_money']){
                               continue;
                           }else{
                               $payids[]=$va['id'];
                               $va['image']=$va->image;
                               $pays[]=$va;
                               $count++;
                               break;

                           }
                       }
                   }else{
                       $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>1,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$ali_pay[0]['id'].',%']])->sum('total')+0;
                       if($money<$ali_pay[0]['max_money']){

                           $payids[]=$ali_pay[0]['id'];
                           $ali_pay[0]['image']=$ali_pay[0]->image;
                           $pays[]=$ali_pay[0];
                           $count++;
                       }

                   }



               }
               $wechat_pay=UserPayType::where(['user_id'=>$order['user_id'],'type'=>2,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
               if($wechat_pay){
                   if(count($wechat_pay)>1){
                       foreach ($wechat_pay as $ke=>$va){
                           $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                           if($money>$v['max_money']){
                               continue;
                           }else{
                               $payids[]=$va['id'];
                               $va['image']=$va->image;
                               $pays[]=$va;
                               $count++;
                               break;

                           }
                       }
                   }else{
                       $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>2,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$wechat_pay[0]['id'].',%']])->sum('total')+0;
                       if($money<$wechat_pay[0]['max_money']){

                           $payids[]=$wechat_pay[0]['id'];
                           $wechat_pay[0]['image']=$wechat_pay[0]->image;
                           $pays[]=$wechat_pay[0];
                           $count++;
                       }

                   }

               }

               $bank_pay=UserPayType::where(['user_id'=>$order['user_id'],'type'=>3,'status'=>1,'is_use'=>1])->order('use_count asc, id asc')->select();
               if($bank_pay){

                   if(count($bank_pay)>1){
                       foreach ($bank_pay as $ke=>$va){
                           $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>3,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$va['id'].',%']])->sum('total')+0;
                           if($money>$va['max_money']){
                               continue;
                           }else{
                               $payids[]=$va['id'];
                               $pays[]=$va;
                               $count++;
                               break;

                           }
                       }
                   }else{
                       $money=OtcOrder::where(['uid'=>$order['user_id'],'state'=>['not in',[4,5,13]],'pay_type'=>3,'create_time'=>['between',[getTodayStart(),getTodayEnd()]],'pay_ids'=>['like','%,'.$bank_pay[0]['id'].',%']])->sum('total')+0;
                       if($money<$wechat_pay[0]['max_money']){

                           $payids[]=$bank_pay[0]['id'];
                           $pays[]=$bank_pay[0];
                           $count++;
                       }

                   }
               }

               if($payids){
                   UserPayType::where(['id'=>['in',$payids]])->setInc('use_count',1);
               }
               if($count==0){
                   //禁止匹配
                   $shop=OtcShop::get(['id'=>$order['shop_id']]);
                   if($shop['no_match_time']>time()){
                       $shop['no_match_time']+=86400;
                   }else{
                       $shop['no_match_time']=86400;
                   }
                   $shop->is_match=0;
                   $shop->save();
                   OtcCancelLog::create([
                       'username'=>$order->member['username'],
                       'mobile'=>$order->member['mobile'],
                       'area'=>$order->member['area'],
                       'number'=>1,
                       'type'=>3,
                       'shop_id'=>$shop['id'],
                       'remark'=>'OTC限制店铺匹配(收款金额超过每日限制)',
                       'user_id'=>$order->member['id']
                   ]);
                   Db::commit();
                   return   [RESULT_ERROR, '出售订单超过每日收款限额,请重新匹配'];
               }
               //商户渠道
               $rndKey = array_rand($channel);
               //写入订单表
               $arr=[
                   'price'=>$order['price'],
                   'wallet_id'=>$order['wallet_id'],
                   'pay_expire_time'=>$time,
                   'otc_type'=>$order['type'],
                   'shop_id'=>$order['shop_id'],
                   'otc_id'=>$order['id'],
                   'user_id'=>$member['id'],
                   'uid'=>$order['user_id'],
                   'total'=>$money,
                   'number'=>$number,
                   'remark'=>'后台生成',
                   'pay_json'=>json_encode($pays),
                   'channel'=>$channel[$rndKey]

               ];
               OtcOrder::create($arr);
               $order->surplus_number=0;
               $order->surplus_total=0;
               $order->state=1;
               $order->match_count+=1;
               $order->save();
               OtcTrading::where(['id'=>$order['id']])->update(['surplus_number'=>0,'state'=>1]);


               OtcShop::where(['id'=>$order['shop_id']])->setInc('total_count',1);
               Db::commit();
           } catch (\Exception $e) {
               Db::rollback();
               return [RESULT_ERROR, $e->getMessage()];
           }

       }

        $url = url('otc/trade_order_list');
        Db::commit();
        return [RESULT_SUCCESS, '生成成功', $url];

    }

    /**
     * Notice信息编辑
     */
    public function orderEdit($data = [])
    {

        if($data['update']==3){
            $url = url('appstore/cash_withdrawal_list');
        }else{
            $url = url('trade_order_list');
        }


        Db::startTrans();
        $info = $this->modelOtcOrder->getInfo(['id' => $data['id']]);
        if (empty($info)) {
            $this->error("订单不存在");
        }
        if ($info['state'] == 2) {
            $this->error("当前订单已完成，无需操作");
        }

        if ($info['state'] == 5) {
            $this->error("当前订单已失败，无需操作");
        }
        try {
            $arr=[
                'update_time'=> TIME_NOW,
                'state'=>$data['state']
            ];
            if($data['state']==5  ){

                //取消退回
                if($info['otc_type']==1){
                    //退币
                    Db::name('transfer')->where(['id'=>$info['withdrwal_id']])->setInc('money',$info['total']);

                }

                Db::name('otc_trading')->where(['id'=>$info['otc_id']])->setInc('surplus_number',$info['number']);


            }elseif($data['state']==2  ){

                $state=2;
                //发币



                if($info['otc_type']==1){
                    $log['remark']='店铺代发买入';
                    $info->shop->number_do+=$info['number'];
                    ShopAccountLog::create([
                        'user_id'=>$info['user_id'],
                        'number'=>$info['number'],
                        'shop_id'=>$info['shop_id'],
                        'remark'=> '购买代发金额',
                        'is_add'=>1,
                        'type'=>4
                    ]);

                }else{


                    //写入流水

                    $user_account=UserAccount::where(['user_id'=>$info['user_id'],'wallet_id'=>1])->lock(true)->find();
                    $money=$info['total'];
                    $user_account->balance+=$money;
                    $user_account->save();

                    //写入流水
                    UserAccountLog::create([
                        'user_id' => $info->user_id,
                        'number' => $money,
                        'wallet_id' =>1,
                        'before_blance' => $user_account->balance -$money,
                        'after_blance' => $user_account->balance,
                        'is_add' => 1,
                        'type' => 24,
                        'remark' =>'OTC买入',

                    ]);
                    //扣除店铺冻结余额
                    $info->shop->number_lock-=$info['number'];
                    if($info->trade->feed_count>0){
                        $info->trade->feed_count=0;
                        $info->trade->save();
                    }
                    if($info->trade->surplus_number==0){
                        $trade_count= Db::name('otc_order')->where(['otc_id'=>$info['otc_id'],'state'=>['in',[1,3,6,7,8]]])->count();
                        if($trade_count>=1){
                            //改变买卖单状态 已完成
                            $info->trade->state=2;
                            $info->trade->save();
                        }
                    }
                }


                $receive_minute=ceil((TIME_NOW-$info->getData('pay_time'))/60);
                SbNotice::create([
                    'type'=>2,
                    'shop_name'=>$info->shop->shop_name,
                    'number'=>$info['number'],
                    'receive_minute'=>$receive_minute,
                    'order_id'=>$info['id'],
                    'user_id'=>$info['user_id'],
                    'wallet_id'=>$info['wallet_id'],

                ]);
                $arr['receive_minute']=$receive_minute;
                $arr['receive_time']=TIME_NOW;
                //更新卖家成交量，发放手续费
                $info->shop->success_count+=1;
                if($info['poundage_number']){
                    $info->shop->poundage_number+=$info['poundage_number'];
                    ShopPoundageLog::create([
                        'user_id'=>$info->shop['user_id'],
                        'shop_id'=>$info['shop_id'],
                        'order_id'=>$info['id'],
                        'otc_id'=>$info['otc_id'],
                        'type'=>$info['withdrwal_id']>0?2:1,
                        'number'=>$info['poundage_number'],
                        'total'=>$info['poundage_number']*$info['price'],
                    ]);
                    $msg= $info->otc_type==1?'代发':'代收';
                    ShopAccountLog::create([
                        'user_id'=>$info->shop['user_id'],
                        'number'=>$info['poundage_number'],
                        'shop_id'=>$info['shop_id'],
                        'remark'=> $msg.'手续费: 0.2%',
                        'is_add'=>1,
                        'type'=>3
                    ]);

                }

                if($info['withdrwal_id']>0){
                    Transfer::where(['id'=>$info['withdrwal_id']])->update(['update_time'=>time(),'state'=>1]);


                }else{
                    $order_count=OtcOrder::where(['shop_id'=>$info['shop_id'],'otc_type'=>2,'state'=>3])->count();
                    if($order_count==0){
                        SbNotice::where(['user_id'=>$info['uid'],'type'=>3])->update(['is_read'=>1]);
                    }
                    user_notice($info['user_id'],'您通过法币交易充值的金额已到账成功，非常感谢您的每一笔交易所积累的诚信，系统将为您记录后将更好的服务您。');

                }
                $info->shop->turnover+=$info['total'];
                $info->shop->save();

            }elseif($data['state']==3){
                if(empty($data['cover_id'])){
                    return  [RESULT_ERROR, '请上传打款截图'];
                }
                $arr['pay_time']=TIME_NOW;
                $arr['receive_expire_time']=time()+getConfig('otc_order_recieve_time')*60;
                SbNotice::create([
                    'type'=>3,
                    'expire_time'=>$arr['receive_expire_time'],
                    'order_id'=>$info['id'],
                    'wallet_id'=>$info['wallet_id'],
                    'user_id'=>$info['uid'],
                    'otc_type'=>$info['withdrwal_id']>0?1:2,

                ]);

                $arr['cover_id']=$data['cover_id'];
                Db::name('otc_order')->where(['id'=>$info['id']])->update($arr);
            }
            $data['update_time']=time();
            $data['admin_name'] = session('member_info.username');


            //修改订单状态
            Db::name('otc_order')->where(['id'=>$info['id']])->update($arr);

            Db::commit();
            return [RESULT_SUCCESS, '操作成功', $url];
        } catch (\Exception $e) {
            Db::rollback();
            return  [RESULT_ERROR, $e->getMessage()];
        }


    }


    /***
     *
     */



}
